1900D - Small GCD - CodeForces Solution


brute force math number theory

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll  long long

vector<ll> q[100005];
void sieve()
{
        for(int i=1;i<=100000;i++)
            {
                for(int j=i;j<=100000;j+=i)
                    {
                        q[j].push_back(i);
                    }
            }
}

int mp1[100005],mp2[100005];
int main()
{
   ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    ll test_cases;
    cin>>test_cases;
    sieve();
    while(test_cases--)
    {
        ll n;
        cin>>n;
        vector<ll> v;
        for(int i=0;i<n;i++){ll temp;cin>>temp;v.push_back(temp);}
        sort(v.begin(),v.end());

        for(auto X:q[v[0]])
            {
                mp1[X]++;
                mp2[X]++;
            }
        ll ans=0;
        for(int i=1;i<n-1;i++)
            {
               ll c_ans=0;
               ll number = v[i];

                for(int j=q[number].size()-1;j>=0;j--)
                    {
                       for(auto K:q[q[number][j]])
                        {
                            if(K==q[number][j]){break;}
                            mp1[K]-=mp1[q[number][j]];
                        }
                    }
                for(int j=0;j<q[number].size();j++)
                    {
                        c_ans+=(mp1[q[number][j]]*q[number][j]);
                        mp2[q[number][j]]++;
                        mp1[q[number][j]]=mp2[q[number][j]];
                    }
                ans+=(c_ans*(n-i-1));
            }
        cout<<ans<<"\n";
        for(int i=0;i<n;i++)
            {
                for(auto X:q[v[i]])
                    {
                        mp1[X]=0;
                        mp2[X]=0;
                    }
            }
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number
279. Perfect Squares
275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II